package com.xxxx.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.xxxx.server.pojo.*;
import com.xxxx.server.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Delete;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lsh
 * @since 2021-03-07
 */
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPoliticsStatusService politicsStatusService;
    @Autowired
    private IJoblevelService joblevelService;
    @Autowired
    private INationService nationService;
    @Autowired
    private IPositionService positionService;
    @Autowired
    private IDepartmentService departmentService;

    /**
     * 查询所有员工(分页)
     * @return
     * 用到分页，肯定有当前页和每页大小，使用@RequestParam接收，defaultValue = "1" 表示当前页是1
     * size，每页大小
     * employee对象
     * 入职日期是一个范围，无法接收，使用数组去接收
     *
     */
    @ApiOperation("查询所有员工")
    @GetMapping("/")
    public RespPageBean getEmployee(@RequestParam(defaultValue = "1") Integer currentPage,
                                    @RequestParam(defaultValue = "10")Integer size,
                                    Employee employee,
                                    LocalDate[] beginDateScope){
        return employeeService.getEmplByPage(currentPage,size,employee,beginDateScope);

    }

    @ApiOperation(value = "获取所有政治面貌")
    @GetMapping("/politicsstatus")
    public List<PoliticsStatus> getAllPoliticsStatus(){
        return politicsStatusService.list();
    }
    @ApiOperation(value = "获取所有职称")
    @GetMapping("/joblevels")
    public List<Joblevel> getAllJoblevel(){
        return joblevelService.list();
    }
    @ApiOperation(value = "获取所有民族")
    @GetMapping("/nations")
    public List<Nation> getAllNation(){
        return nationService.list();
    }
    @ApiOperation(value = "获取所有职位")
    @GetMapping("/positions")
    public List<Position> getAllPosition(){
        return positionService.list();
    }
    // 父子部门
    @ApiOperation(value = "获取所有部门")
    @GetMapping("/deps")
    public List<Department> getAllDepartment(){
        return departmentService.getAllDepartment();
    }
    @ApiOperation(value = "获取最新工号")
    @GetMapping("/maxWorkID")
    public RespBean maxWorkID(){
        return employeeService.maxWorkID();
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @ApiOperation(value = "添加员工")
    @PostMapping("/")
    public RespBean addEmployee(@RequestBody Employee employee){
        return employeeService.addEmployee(employee);
    }
    /**
     * 更新员工（不考虑合同期限）
     */
    @ApiOperation(value = "更新员工")
    @PutMapping("/")
    public RespBean updateEmpl(@RequestBody Employee employee){
        if(employeeService.updateById(employee)){
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    @ApiOperation(value = "删除员工")
    @Delete("/{id}")
    public RespBean deleteEmpl(@PathVariable Integer id){
        if (employeeService.removeById(id)){
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    /**
     *  导出员工数据
     *  查询所有员工数据 和 指定id员工数据
     *  从exportEmployee中以流的形式导出数据需要HttpServletResponse
     *  获取当前所有员工数据
     *  produces = "application/octet-stream" ,以流的形式输出，不然会乱码
     */
    @ApiOperation(value = "导出员工数据")
    @GetMapping(value = "/export",produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response){
        // 获取数据
        List<Employee> list = employeeService.getEmplById(null);
        /**
         * 添加导出参数 ExportParams ，可以加参数：导出之后文件名，导出之后表格名，导出excel版本
         * 使用工具类ExcelExportUtil的exportExcel（），把参数，对象，数据放入并以流的形式导出，获得workbook
         * 输出workbook，准备一个response输出流,并捕获异常
         * 捕获数据之前还需要再设置一些头信息，因为导出的为excel
         */
        ExportParams exportParams = new ExportParams("员工表","员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Employee.class, list);
        ServletOutputStream outputStream = null ;
        try {
            //流的形式传出
            response.setHeader("content-type","application/octet-stream");
            //放置中文乱码
            response.setHeader("content-disposition",
                    "attachment;filename=" + URLEncoder.encode("员工表.xls","UTF-8"));
            outputStream = response.getOutputStream();
            // 流的形式输出
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 关闭流之前，判断
            if(null!=outputStream){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @ApiOperation(value = "导入数据")
    @PostMapping("/import")
    // 文件参数 MultipartFile ，导入和导出一样，需要参数，字节码文件
    public RespBean importEmpl(MultipartFile file){
        ImportParams importParams = new ImportParams();
        // 删除第一行标题行
        importParams.setTitleRows(1);
        List<Nation> nationList = nationService.list();
        // 导入数据
        try {
            List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, importParams);
            //获取NationId，重写了Equals和HashCode，并且准备了有参构造，并且设置name为必填。
            list.forEach(employee -> {
                // 获取Nation对象的name
                // 有了nationList，使用indexOf，获取下标，再用get，获取完整的Nation对象，此时有id，有name等
                // 再getId 去获取id
                Integer nationId = nationList.get(
                                    nationList.indexOf(
                                            new Nation(employee.getNation().getName())
                                    )
                            ).getId();
                employee.setNationId(nationId);
            });
            if (employeeService.saveBatch(list)){
                return RespBean.success("导入成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败");
    }

}
